<?php

namespace System;

use System\Entity\Response;

class PageLoader {
    private $getData;
    private $postData;
    private $route;
    private $controller;
    private $parameters;

    public function setGetData($getData) {
        $this->getData = $getData;
    }

    public function setPostData($postData) {
        $this->postData = $postData;
    }

    public function setRoute($route) {
        $this->route = $route;
    }

    private function instantiateController($controllerPath, $controller) {
        $temp = \Library\ClassTrigger::instantiate($controllerPath, $controller);
        if ($temp === false)
            return false;
        $this->controller = $temp;
        return true;
    }

    private function initiateParameters() {
        $this->parameters = array_merge($this->getData, $this->postData);
    }

    private function invokeMethod($methodName) {
        return \Library\ClassTrigger::invokeArgs($this->controller, $methodName, $this->parameters);
    }

    public function load() {
        $controllerPath = $this->route->getControllerPath();
        $controller = $this->route->getController();
        $entryAction = $this->route->getEntryAction();
        $action = $this->route->getAction();

        if (!$this->instantiateController($controllerPath, $controller))
            return new Response("HTML", "Fail: Cannot initiate class (Wrong path?): " . $controllerPath);

        $this->initiateParameters();

        
        if ($this->invokeMethod($entryAction) === false)
            return new Response("HTML", "Fail: Cannot authenticate on EntryAction: " . $entryAction);

        
        $response = $this->invokeMethod($action);
        if ($response === false)
            return new Response("HTML", "Fail: Cannot invoke method for Controller: " . $action);
        return $response;
    }
}